<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>部门生产绩效填报</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'arial';
            background-color: #f5f5f5;
        }

        .container {
            height: 100vh;
            display: flex;
            flex-direction: column;
            padding: 10px 10px 0px 10px;
            box-sizing: border-box;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            text-align: center;
        }

        .header h1 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }

        .header p {
            margin: 0;
            opacity: 0.9;
            font-size: 16px;
        }

        .toolbar {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .main-content {
            flex: 1;
            padding-top: 10px;
            overflow: auto;
        }

        .performance-table {
            background: white;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            padding: 15px;
        }

        .performance-table .el-table__body td {
            padding: 0px 0;
        }

        .el-table__body-wrapper {
            overflow-y: auto !important;
            overflow-x: auto;
        }

        .action-buttons {
            display: inline-block;
            gap: 10px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #909399;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            display: block;
        }

        .performance-percentage {
            font-weight: bold;
            color: #409eff;
        }

        .performance-percentage.high {
            color: #67c23a;
        }

        .performance-percentage.low {
            color: #e6a23c;
        }

        .performance-percentage.critical {
            color: #f56c6c;
        }

        .status-tag {
            font-size: 12px;
        }

        /* Batch edit dialog styles */
        .batch-edit-form {
            max-height: calc(80vh - 200px);
            overflow-y: auto;
        }

        .bu-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 3px 10px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            margin-bottom: 6px;
            background: #fafafa;
            min-height: 36px;
        }

        .bu-name {
            font-weight: 500;
            color: #2c3e50;
            flex: 1;
            line-height: 1.2;
        }

        .division-bu-info {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .division-tag {
            font-size: 11px;
            font-weight: 600;
            color: #409eff;
            background: #ecf5ff;
            padding: 2px 6px;
            border-radius: 3px;
            white-space: nowrap;
        }

        .bu-text {
            font-size: 13px;
            font-weight: 500;
        }

        .performance-input {
            width: 150px;
            margin-left: 15px;
        }

        .operation-buttons {
            display: flex;
            gap: 5px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <!-- <div class="header">
                <h1>部门生产绩效填报</h1>
                <p>管理各BU的生产绩效数据填报与查看</p>
            </div> -->

            <div class="toolbar">
                <div>
                    <h3>生产绩效管理</h3>
                </div>
                <div style="display: flex; align-items: center; gap: 15px;">
                    <el-form :inline="true" size="small">
                        <el-form-item label="月份">
                            <el-date-picker v-model="selectedDate" type="month" placeholder="选择月份" format="yyyy年MM月"
                                value-format="yyyy-MM" clearable style="width: 150px;">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="applyFilter" icon="el-icon-search"
                                size="small">筛选</el-button>
                            <el-button @click="resetFilter" icon="el-icon-refresh" size="small">重置</el-button>
                        </el-form-item>
                        <div class="action-buttons">
                            <el-button type="primary" size="small" @click="showBatchEditDialog" icon="el-icon-edit">
                                编辑全部
                            </el-button>
                            <el-button size="small" @click="refreshData" icon="el-icon-refresh">
                                刷新
                            </el-button>
                        </div>
                    </el-form>

                </div>
            </div>

            <div class="main-content">
                <div v-if="performanceList.length === 0" class="empty-state">
                    <i class="el-icon-document"></i>
                    <p>暂无生产绩效数据</p>
                    <p style="font-size: 12px;">点击"编辑全部"开始填报各BU的生产绩效</p>
                </div>

                <div v-else class="performance-table">
                    <el-table :data="filteredPerformanceList" border style="width: 100%;" :height="tableMaxHeight()"
                        stripe>
                        <el-table-column prop="division" label="Division" min-width="200" fixed="left">
                            <template slot-scope="scope">
                                <div style="font-weight: 500; color: #2c3e50;">{{ scope.row.division }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="buName" label="BU名称" min-width="300">
                            <template slot-scope="scope">
                                <div style="font-weight: 500;">{{ scope.row.buName }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="month" label="月份" width="120" align="center">
                            <template slot-scope="scope">
                                <div style="font-weight: 500; color: #409eff;">{{ scope.row.year }}年{{ scope.row.month
                                    }}月</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="performancePercentage" label="生产绩效百分比" width="150" align="center">
                            <template slot-scope="scope">
                                <div v-if="scope.row.performancePercentage !== null"
                                    :class="getPerformanceClass(scope.row.performancePercentage)"
                                    class="performance-percentage">
                                    {{ scope.row.performancePercentage }}%
                                </div>
                                <span v-else style="color: #909399;">未填报</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="status" label="状态" width="100" align="center">
                            <template slot-scope="scope">
                                <el-tag :type="getStatusType(scope.row.status)" size="small" class="status-tag">
                                    {{ getStatusText(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column prop="submitter" label="提交人" width="120" align="center">
                            <template slot-scope="scope">
                                <span v-if="scope.row.submitter">{{ scope.row.submitter }}</span>
                                <span v-else style="color: #909399;">-</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="submitTime" label="提交时间" width="160" align="center">
                            <template slot-scope="scope">
                                <span v-if="scope.row.submitTime">{{ formatDateTime(scope.row.submitTime) }}</span>
                                <span v-else style="color: #909399;">-</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="modifier" label="修改人" width="120" align="center">
                            <template slot-scope="scope">
                                <span v-if="scope.row.modifier">{{ scope.row.modifier }}</span>
                                <span v-else style="color: #909399;">-</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="modifyTime" label="修改时间" width="160" align="center">
                            <template slot-scope="scope">
                                <span v-if="scope.row.modifyTime">{{ formatDateTime(scope.row.modifyTime) }}</span>
                                <span v-else style="color: #909399;">-</span>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="120" align="center" fixed="right">
                            <template slot-scope="scope">
                                <div class="operation-buttons">
                                    <el-button type="text" size="small" @click="editSingleBU(scope.row)"
                                        style="color: #409eff;">
                                        编辑
                                    </el-button>
                                    <!-- <el-button type="text" size="small" @click="viewHistory(scope.row)"
                                        style="color: #67c23a;">
                                        历史
                                    </el-button> -->
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <!-- 批量编辑对话框 -->
        <el-dialog title="批量填写生产绩效" :visible.sync="batchEditDialogVisible" width="800px" :modal-append-to-body="false">
            <div class="batch-edit-form">
                <div style="margin-bottom: 15px; color: #606266; font-size: 14px;">
                    <i class="el-icon-info"></i>
                    请为以下各BU填写生产绩效百分比（0-200%）
                    <span v-if="selectedDate" style="color: #409eff; font-weight: 600; margin-left: 10px;">
                        （当前月份：{{ formatSelectedMonth() }}）
                    </span>
                </div>

                <div v-for="bu in batchEditData" :key="bu.id" class="bu-item">
                    <div class="bu-name">
                        <div class="division-bu-info">
                            <span class="division-tag">{{ bu.division }}</span>
                            <span class="bu-text">{{ bu.buName }}</span>
                        </div>
                    </div>
                    <el-input-number v-model="bu.performancePercentage" class="performance-input" :min="0" :max="200"
                        :precision="1" size="small" placeholder="请输入百分比" controls-position="right">
                    </el-input-number>
                </div>
            </div>

            <div slot="footer" class="dialog-footer">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div style="color: #606266; font-size: 12px;">
                        提示：填写后将自动记录提交人和提交时间
                    </div>
                    <div>
                        <el-button @click="batchEditDialogVisible = false" size="small">取消</el-button>
                        <el-button type="primary" @click="saveBatchEdit" size="small">保存全部</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 单个BU编辑对话框 -->
        <el-dialog title="编辑BU生产绩效" :visible.sync="singleEditDialogVisible" width="500px" :modal-append-to-body="false">
            <el-form :model="singleEditForm" label-width="120px">
                <el-form-item label="BU名称">
                    <el-input v-model="singleEditForm.buName" readonly></el-input>
                </el-form-item>
                <el-form-item label="生产绩效百分比" required>
                    <el-input-number v-model="singleEditForm.performancePercentage" :min="0" :max="200" :precision="1"
                        style="width: 100%;" placeholder="请输入百分比" controls-position="right">
                    </el-input-number>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="singleEditDialogVisible = false" size="small">取消</el-button>
                <el-button type="primary" @click="saveSingleEdit" size="small">保存</el-button>
            </div>
        </el-dialog>

        <!-- 历史记录对话框 -->
        <el-dialog title="历史记录" :visible.sync="historyDialogVisible" width="700px" :modal-append-to-body="false">
            <el-table :data="historyData" border>
                <el-table-column prop="performancePercentage" label="生产绩效%" width="120" align="center">
                    <template slot-scope="scope">
                        <span class="performance-percentage">{{ scope.row.performancePercentage }}%</span>
                    </template>
                </el-table-column>
                <el-table-column prop="operator" label="操作人" width="120" align="center"></el-table-column>
                <el-table-column prop="operationType" label="操作类型" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.operationType === '新增' ? 'success' : 'primary'" size="mini">
                            {{ scope.row.operationType }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="operationTime" label="操作时间" align="center">
                    <template slot-scope="scope">
                        {{ formatDateTime(scope.row.operationTime) }}
                    </template>
                </el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button @click="historyDialogVisible = false" size="small">关闭</el-button>
            </div>
        </el-dialog>
    </div>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    // Division-BU清单
                    divisionBuList: [
                        { division: 'Body', bu: 'TRB' },
                        { division: 'Body', bu: 'TRPH Shenyang' },
                        { division: 'Chassis', bu: 'Coil Spring Shenyang' },
                        { division: 'Chassis', bu: 'Coil Spring Taicang' },
                        { division: 'Chassis', bu: 'Coil Spring Taicang Prototype' },
                        { division: 'Chassis', bu: 'Divisional TS Chassis' },
                        { division: 'Chassis', bu: 'ITW Shenyang' },
                        { division: 'Chassis', bu: 'ITW Taicang' },
                        { division: 'Chassis', bu: 'Plant Chassis Shenyang' },
                        { division: 'Chassis', bu: 'Plant Chassis Taicang' },
                        { division: 'Chassis', bu: 'Stabilizer Bar Taicang' },
                        { division: 'Powertrain / Industry', bu: 'Belt Tensioner Taicang' },
                        { division: 'Powertrain / Industry', bu: 'Connecting Products Taicang' },
                        { division: 'Powertrain / Industry', bu: 'DAT' },
                        { division: 'Powertrain / Industry', bu: 'Disc Spring Taicang' },
                        { division: 'Powertrain / Industry', bu: 'Plant PTI Taicang' },
                        { division: 'Powertrain / Industry', bu: 'SES' },
                        { division: 'Powertrain / Industry', bu: 'Transmission Disc Spring Taicang' },
                        { division: 'Powertrain / Industry', bu: 'Tubular Shaft' },
                        { division: 'Powertrain / Industry', bu: 'Valve Spring Taicang' },
                        { division: 'Regional Technical Service', bu: 'Regional TS China' },
                        { division: 'Regional Technical Service', bu: 'Site Taicang' },
                        { division: 'Toolshop', bu: 'Toolshop' },
                        { division: 'Tubes', bu: 'MPST Yangzhou' }
                    ],
                    performanceList: [],
                    batchEditDialogVisible: false,
                    singleEditDialogVisible: false,
                    historyDialogVisible: false,
                    batchEditData: [],
                    singleEditForm: {
                        id: '',
                        buName: '',
                        performancePercentage: null
                    },
                    historyData: [],
                    currentUser: '系统管理员', // 模拟当前用户
                    selectedDate: null // 日期选择器选中的日期
                }
            },
            computed: {
                // 按Division和BU名称排序的性能列表
                sortedPerformanceList() {
                    return [...this.performanceList].sort((a, b) => {
                        // 首先按Division排序
                        if (a.division !== b.division) {
                            return a.division.localeCompare(b.division);
                        }
                        // 然后按BU名称排序
                        return a.buName.localeCompare(b.buName);
                    });
                },
                // 按月份过滤后的性能列表
                filteredPerformanceList() {
                    let filtered = this.sortedPerformanceList;
                    if (this.selectedDate) {
                        const selectedMonth = parseInt(this.selectedDate.split('-')[1]);
                        const selectedYear = parseInt(this.selectedDate.split('-')[0]);
                        // 过滤指定月份的数据，如果没有则创建
                        filtered = filtered.filter(item => item.month === selectedMonth && item.year === selectedYear);

                        // 如果过滤后没有数据，为每个Division-BU创建当月数据
                        if (filtered.length === 0) {
                            filtered = this.divisionBuList.map((item, index) => ({
                                id: `bu_${selectedYear}_${selectedMonth}_${index + 1}`,
                                division: item.division,
                                buName: item.bu,
                                month: selectedMonth,
                                year: selectedYear,
                                performancePercentage: null,
                                status: 'pending',
                                submitter: null,
                                submitTime: null,
                                modifier: null,
                                modifyTime: null,
                                history: []
                            }));
                            // 将新创建的数据添加到performanceList中
                            this.performanceList.push(...filtered);
                            this.savePerformanceData();
                        }
                    } else {
                        // 如果没有选择月份，显示当前月份的数据
                        const currentMonth = new Date().getMonth() + 1;
                        const currentYear = new Date().getFullYear();
                        filtered = filtered.filter(item => item.month === currentMonth && item.year === currentYear);
                    }
                    return filtered;
                }
            },
            mounted() {
                this.initializeData();
                this.loadPerformanceData();
                window.addEventListener('resize', () => { this.$forceUpdate() });
            },
            methods: {

                tableMaxHeight() {
                    // 计算表格最大高度：视窗高度 - 头部 - 标签页 - 其他元素
                    const headerHeight = 100; // 头部高度
                    const tabHeight = 50; // 标签页高度（包括padding和margin）
                    const height = window.innerHeight - headerHeight - tabHeight;
                    return Math.max(height, 200); // 确保最小高度
                },

                // 初始化数据
                initializeData() {
                    const stored = localStorage.getItem('departmentPerformanceData');
                    if (!stored) {
                        // 如果没有存储数据，初始化所有Division-BU的数据结构
                        const currentMonth = new Date().getMonth() + 1;
                        const currentYear = new Date().getFullYear();
                        const initialData = this.divisionBuList.map((item, index) => ({
                            id: `bu_${currentYear}_${currentMonth}_${index + 1}`,
                            division: item.division,
                            buName: item.bu,
                            month: currentMonth,
                            year: currentYear,
                            performancePercentage: null,
                            status: 'pending', // pending, submitted, modified
                            submitter: null,
                            submitTime: null,
                            modifier: null,
                            modifyTime: null,
                            history: []
                        }));
                        localStorage.setItem('departmentPerformanceData', JSON.stringify(initialData));
                    }
                },

                // 加载绩效数据
                loadPerformanceData() {
                    const stored = localStorage.getItem('departmentPerformanceData');
                    if (stored) {
                        this.performanceList = JSON.parse(stored);
                    }
                },

                // 保存绩效数据
                savePerformanceData() {
                    localStorage.setItem('departmentPerformanceData', JSON.stringify(this.performanceList));
                },

                // 显示批量编辑对话框
                showBatchEditDialog() {
                    this.batchEditData = [...this.filteredPerformanceList].map(item => ({
                        ...item,
                        performancePercentage: item.performancePercentage || 0
                    }));
                    this.batchEditDialogVisible = true;
                },

                // 保存批量编辑
                saveBatchEdit() {
                    const now = new Date().toISOString();
                    let updateCount = 0;

                    this.batchEditData.forEach(batchItem => {
                        const originalItem = this.performanceList.find(item => item.id === batchItem.id);
                        if (originalItem && batchItem.performancePercentage !== null) {
                            const isModification = originalItem.performancePercentage !== null;

                            // 记录历史
                            const historyRecord = {
                                performancePercentage: batchItem.performancePercentage,
                                operator: this.currentUser,
                                operationType: isModification ? '修改' : '新增',
                                operationTime: now
                            };

                            if (!originalItem.history) {
                                originalItem.history = [];
                            }
                            originalItem.history.push(historyRecord);

                            // 更新数据
                            originalItem.performancePercentage = batchItem.performancePercentage;

                            if (isModification) {
                                originalItem.modifier = this.currentUser;
                                originalItem.modifyTime = now;
                                originalItem.status = 'modified';
                            } else {
                                originalItem.submitter = this.currentUser;
                                originalItem.submitTime = now;
                                originalItem.status = 'submitted';
                            }

                            updateCount++;
                        }
                    });

                    this.savePerformanceData();
                    this.batchEditDialogVisible = false;
                    this.$message.success(`批量更新完成，共更新 ${updateCount} 个BU的数据`);
                },

                // 编辑单个BU
                editSingleBU(row) {
                    this.singleEditForm = {
                        id: row.id,
                        buName: row.buName,
                        performancePercentage: row.performancePercentage || 0
                    };
                    this.singleEditDialogVisible = true;
                },

                // 保存单个编辑
                saveSingleEdit() {
                    if (this.singleEditForm.performancePercentage === null) {
                        this.$message.warning('请输入生产绩效百分比');
                        return;
                    }

                    const now = new Date().toISOString();
                    const originalItem = this.performanceList.find(item => item.id === this.singleEditForm.id);

                    if (originalItem) {
                        const isModification = originalItem.performancePercentage !== null;

                        // 记录历史
                        const historyRecord = {
                            performancePercentage: this.singleEditForm.performancePercentage,
                            operator: this.currentUser,
                            operationType: isModification ? '修改' : '新增',
                            operationTime: now
                        };

                        if (!originalItem.history) {
                            originalItem.history = [];
                        }
                        originalItem.history.push(historyRecord);

                        // 更新数据
                        originalItem.performancePercentage = this.singleEditForm.performancePercentage;

                        if (isModification) {
                            originalItem.modifier = this.currentUser;
                            originalItem.modifyTime = now;
                            originalItem.status = 'modified';
                        } else {
                            originalItem.submitter = this.currentUser;
                            originalItem.submitTime = now;
                            originalItem.status = 'submitted';
                        }

                        this.savePerformanceData();
                        this.singleEditDialogVisible = false;
                        this.$message.success('保存成功');
                    }
                },

                // 查看历史记录
                viewHistory(row) {
                    this.historyData = row.history || [];
                    this.historyDialogVisible = true;
                },

                // 获取绩效等级样式
                getPerformanceClass(percentage) {
                    if (percentage >= 120) return 'high';
                    if (percentage >= 100) return '';
                    if (percentage >= 80) return 'low';
                    return 'critical';
                },

                // 获取状态类型
                getStatusType(status) {
                    switch (status) {
                        case 'submitted': return 'success';
                        case 'modified': return 'primary';
                        case 'pending': return 'info';
                        default: return 'info';
                    }
                },

                // 获取状态文本
                getStatusText(status) {
                    switch (status) {
                        case 'submitted': return '已提交';
                        case 'modified': return '已修改';
                        case 'pending': return '待填报';
                        default: return '待填报';
                    }
                },

                // 格式化日期时间
                formatDateTime(dateTimeString) {
                    if (!dateTimeString) return '-';
                    const date = new Date(dateTimeString);
                    return date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                },

                // 刷新数据
                refreshData() {
                    this.loadPerformanceData();
                    this.$message.success('数据已刷新');
                },

                // 获取唯一Division列表
                getUniqueDivisions() {
                    const divisions = [...new Set(this.performanceList.map(item => item.division))];
                    return divisions.sort();
                },

                // 应用过滤器
                applyFilter() {
                    // 过滤逻辑已在computed属性中实现
                    this.$message.success('过滤条件已应用');
                },

                // 重置过滤器
                resetFilter() {
                    this.selectedDate = null;
                    this.$message.success('过滤条件已重置');
                },

                // 格式化选中的月份显示
                formatSelectedMonth() {
                    if (!this.selectedDate) return '';
                    const year = this.selectedDate.split('-')[0];
                    const month = this.selectedDate.split('-')[1];
                    return `${year}年${parseInt(month)}月`;
                }
            }
        });
    </script>
</body>

</html>